package jyj.springmvc.learning.controller;

import jyj.springmvc.learning.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author 老顽固小可爱
 * @Date 2022/12/12 18:59
 * @Version 1.0
 */
@Controller
public class LoginController {
    /**
     * 登录
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        //验证用户名和密码
        if (user != null && "admin".equals(user.getPassword()) && "admin".equals(user.getUserName())) {
            HttpSession session = request.getSession();
            //将用户信息放到 session 域中
            session.setAttribute("loginUser", user);
            //重定向到商品列表
            return "redirect:/main";
        }
        //提示用户名或密码错误
        request.setAttribute("msg", "用户名或密码错误");
        return "login";
    }

    /**
     * 登出
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public String Logout(User user, HttpServletRequest request) {
        //session 失效
        request.getSession().invalidate();
        return "redirect:/";
    }
}

